from django.urls import path, reverse
from django.utils.safestring import mark_safe

from stark.service.v1 import StarkHandler, get_choice_text, get_manytomany, BootStrapModelForm, SearchOption
from web.models import ScoreRecord


class ScoreRecordModelForm(BootStrapModelForm):
    class Meta:
        model = ScoreRecord
        fields = ['content', 'score']


class StudentScoreHandler(StarkHandler):
    list_display = ['content', 'score', 'user']
    model_form_class = ScoreRecordModelForm

    def get_list_display(self):
        value = []
        if self.list_display:
            value.extend(self.list_display)
        return value

    def get_urls(self):
        """
      积分不能编辑和删除
      :return:
      """
        patterns = []
        patterns.append(path('list/<int:student_id>/', self.wapper(self.list_view), name=self.get_list_url_name))
        patterns.append(path('add/<int:student_id>/', self.wapper(self.add_view), name=self.get_add_url_name))
        patterns.extend(self.extra_urls())
        # print(patterns)
        return patterns

    def get_query_set(self, request, *args, **kwargs):
        student_id = kwargs.get('student_id')

        return self.model_class.objects.filter(student_id=student_id)

    def save(self, request, form, is_update, *args, **kwargs):
        student_id = kwargs.get('student_id')
        user_id = request.session['user_info']['id']
        form.instance.student_id = student_id
        form.instance.user_id = user_id
        form.save()

        score = form.instance.score
        if score > 0:
            form.instance.student.score += abs(score)
        else:
            form.instance.student.score -= abs(score)
        form.instance.student.save()
